import json
import hashlib
import time
import os
from typing import Dict, Any, Optional
from pathlib import Path


class CacheManager:
    """响应缓存管理器"""
    
    def __init__(self, cache_dir: str = "cache", max_size: int = 1000, ttl: int = 3600):
        """
        初始化缓存管理器
        
        Args:
            cache_dir: 缓存目录
            max_size: 最大缓存条目数
            ttl: 缓存有效期（秒）
        """
        self.cache_dir = Path(cache_dir)
        self.max_size = max_size
        self.ttl = ttl
        self.cache_file = self.cache_dir / "response_cache.json"
        
        # 确保缓存目录存在
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        
        # 加载现有缓存
        self.cache = self._load_cache()
    
    def _load_cache(self) -> Dict[str, Dict[str, Any]]:
        """从文件加载缓存"""
        if self.cache_file.exists():
            try:
                with open(self.cache_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except (json.JSONDecodeError, FileNotFoundError):
                return {}
        return {}
    
    def _save_cache(self):
        """保存缓存到文件"""
        try:
            with open(self.cache_file, 'w', encoding='utf-8') as f:
                json.dump(self.cache, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存缓存失败: {e}")
    
    def _generate_cache_key(self, messages: list, model_name: str, enable_thinking: bool) -> str:
        """生成缓存键"""
        # 使用消息内容、模型名称和思考模式生成唯一键
        cache_data = {
            "messages": messages,
            "model_name": model_name,
            "enable_thinking": enable_thinking
        }
        
        # 使用SHA256生成哈希键
        key_str = json.dumps(cache_data, sort_keys=True, ensure_ascii=False)
        return hashlib.sha256(key_str.encode('utf-8')).hexdigest()
    
    def get(self, messages: list, model_name: str, enable_thinking: bool) -> Optional[str]:
        """
        从缓存中获取响应
        
        Args:
            messages: 消息列表
            model_name: 模型名称
            enable_thinking: 是否启用深度思考
            
        Returns:
            缓存的响应内容，如果不存在或已过期则返回None
        """
        cache_key = self._generate_cache_key(messages, model_name, enable_thinking)
        
        if cache_key in self.cache:
            cache_entry = self.cache[cache_key]
            
            # 检查缓存是否过期
            current_time = time.time()
            if current_time - cache_entry['timestamp'] <= self.ttl:
                # 更新最后访问时间
                cache_entry['last_accessed'] = current_time
                self._save_cache()
                return cache_entry['response']
            else:
                # 缓存已过期，删除
                del self.cache[cache_key]
                self._save_cache()
        
        return None
    
    def set(self, messages: list, model_name: str, enable_thinking: bool, response: str):
        """
        设置缓存
        
        Args:
            messages: 消息列表
            model_name: 模型名称
            enable_thinking: 是否启用深度思考
            response: 响应内容
        """
        cache_key = self._generate_cache_key(messages, model_name, enable_thinking)
        current_time = time.time()
        
        # 检查缓存大小，如果超过限制则删除最旧的条目
        if len(self.cache) >= self.max_size:
            # 找到最久未访问的条目
            oldest_key = min(
                self.cache.keys(), 
                key=lambda k: self.cache[k].get('last_accessed', 0)
            )
            del self.cache[oldest_key]
        
        # 添加新的缓存条目
        self.cache[cache_key] = {
            'response': response,
            'timestamp': current_time,
            'last_accessed': current_time,
            'model_name': model_name,
            'enable_thinking': enable_thinking
        }
        
        self._save_cache()
    
    def clear(self):
        """清空所有缓存"""
        self.cache = {}
        self._save_cache()
    
    def get_stats(self) -> Dict[str, Any]:
        """获取缓存统计信息"""
        current_time = time.time()
        valid_entries = 0
        expired_entries = 0
        
        for entry in self.cache.values():
            if current_time - entry['timestamp'] <= self.ttl:
                valid_entries += 1
            else:
                expired_entries += 1
        
        return {
            'total_entries': len(self.cache),
            'valid_entries': valid_entries,
            'expired_entries': expired_entries,
            'max_size': self.max_size,
            'ttl': self.ttl
        }
    
    def cleanup_expired(self):
        """清理过期的缓存条目"""
        current_time = time.time()
        keys_to_remove = []
        
        for key, entry in self.cache.items():
            if current_time - entry['timestamp'] > self.ttl:
                keys_to_remove.append(key)
        
        for key in keys_to_remove:
            del self.cache[key]
        
        if keys_to_remove:
            self._save_cache()
            print(f"清理了 {len(keys_to_remove)} 个过期缓存条目")


# 全局缓存实例
cache_manager = CacheManager()